<script setup lang="ts">
import { onActivated, onDeactivated } from "vue"
import { ref } from "vue"
import { useRouter } from "vue-router"
import _ from "lodash"
import fetch from "@/api/fetch.js"
import useAppStore from "@/pinia"
const app = useAppStore()

import { useI18n } from "vue-i18n"
const { t } = useI18n()

const listEl = ref()
const loginEl = ref()
const meEl = ref()
const ChatList = ref(null) as any
import { useScroll, useElementSize, useWebNotification } from "@vueuse/core"
const { y: scrollHeight } = useScroll(listEl)
const { height } = useElementSize(listEl)

const hasLoadFile = ref(true) // 是否加载媒体文件再进入 开发用 默认true

// const scroll = () => {
//   console.log('scrollHeight',scrollHeight.value)
//   console.log('height',height.value)
// }

const router = useRouter()
const routerPush = (path: any, click: boolean = false) => {
    if (click) buttonClick()
    if (hasQuickMatch.value) quickMatch() // 取消匹配
    router.replace({
        path,
    })
}

const toMulti = () => {
    router.replace({
        path: "/multi",
    })
    return
    buttonClick()
    if (app.isLogin) {
        // return app.showTopMessage('working...', 'info')
        router.replace({
            path: "/multi",
        })
    } else loginEl.value.show()
}

const toMe = () => {
    buttonClick()
    if (app.isLogin) {
        meEl.value.show()
    } else loginEl.value.show()
}

const toRank = () => {
    buttonClick()
    if (app.isLogin) {
        return app.showTopMessage("working...", "info")
        router.replace({
            path: "/rank",
        })
    } else loginEl.value.show()
}

//  Particles start
import { particlesOptions } from "@/utils/particlesOptions"
let Options = particlesOptions() as any // 初始配置
const particlesHasInit = ref(false)
let container = null as any // 容器实例

const particlesLoaded = async (el: any) => {
    console.log("index Particles 加载完成", el)
    particlesHasInit.value = true
    container = el
}

onActivated(() => {
    if (firstEnter.value) {
        if (!hasLoadFile.value) isLoadEnd.value = true
        // 预加载音频完毕
        setTimeout(() => {
            // 确保audioBase已经挂载完毕
            if (app.audioBase.hasActionOnLoadCallback) {
                app.playBgm("index")
                isLoadEnd.value = true
            } else
                app.audioBase.onLoadCallback = () => {
                    app.playBgm("index")
                    isLoadEnd.value = true
                }
        }, 1000)
    } else app.playBgm("index")
    if (container) {
        container.refresh()
        particlesHasInit.value = true
    }

    // 回到首页后 是否自动开启匹配
    let quickMatchOn = sessionStorage.getItem("quickMatchOn")
    if (quickMatchOn) {
        sessionStorage.removeItem("quickMatchOn")
        setTimeout(() => {
            quickMatch()
        }, 600)
    }

    // 大厅版聊滚动到最下方
    ChatList.value.scrollTop = ChatList.value.scrollHeight
})

onDeactivated(() => {
    if (container) {
        container.pause()
        container.stop()
    }
    particlesHasInit.value = false
})

//  Particles end

const firstEnter = ref(true)
const isLoadEnd = ref(false)
const firstEnterMaskClick = () => {
    if (!isLoadEnd.value) return
    firstEnter.value = false
    if (app.isLogin) app.showMessage(`${t("index.haveFun")} ${app.userInfo.name}`, 2, "success", 3000, t("index.welcome"))
}

const onMessage = (e: any) => {
    let { content } = e
    if (content) {
        content = JSON.parse(content)
        console.log("content", content)
        let self = content.user.userId == app.userInfo.userId
        if (self) return
        hallChatList.value.push(content)
        setTimeout(() => {
            // 大厅版聊滚动到最下方
            ChatList.value.scrollTop = ChatList.value.scrollHeight
        }, 100)
    }
}
const loginEnd = () => {
    app.initIo() // 初始化心跳
    app.goEasyBase.subscribeGoEasy("indexChat") // 加入 首页群聊 频道
    app.goEasyBase.onMessage("index", onMessage) // 监听 首页群聊 频道消息
}

const hallChatList = ref([]) as any // 大厅聊天列表
// 大厅发送信息
const sendMessageHall = (e: any) => {
    if (!app.isLogin) {
        e.target.value = ""
        return app.showMessage("请先登录")
    }
    let val = e.target.value
    // 剔除两侧空格
    val = val.trim()
    if (val == "") return
    app.goEasyBase.sendMessage("indexChat", "sendIndexChat", val) // 在 首页群聊 频道 发送信息
    hallChatList.value.push({
        message: val,
        user: {
            userId: app.userInfo.userId,
            name: app.userInfo.name,
        },
    })
    e.target.value = ""
}

// 监听离线
const handleOffline = () => {
    quickMatch() // 退出匹配
}

const { show: showMatchSuccessTip } = useWebNotification({
    title: "匹配成功，请尽快前往游戏",
    dir: "auto",
    lang: "zh-CN",
    renotify: true,
    tag: "匹配成功",
})

// 是否正在匹配
const hasQuickMatch = ref(false)
// 加入匹配 / 退出匹配
const quickMatch = (click: boolean = false) => {
    if (click) buttonClick()
    if (!app.online) return app.showMessage("当前网络异常，请检查网络状态后重试")
    if (!app.isLogin && !hasQuickMatch.value) return loginEl.value.show() // 未登录加入匹配
    hasQuickMatch.value = !hasQuickMatch.value
    if (hasQuickMatch.value) {
        app.joinMatch()
        app.injectIoCb("matchSuccess", matchSuccess) // 挂载匹配成功回调
        // 监听离线
        window.addEventListener("offline", handleOffline)
    } else {
        app.exitMatch()
        // 移除监听
        window.removeEventListener("offline", handleOffline)
    }
}

const matchSuccess = (data: any) => {
    if (hasQuickMatch.value) {
        showMatchSuccessTip()
        hasQuickMatch.value = false
        console.log("matchSuccess", data)
        app.roomId = data.roomId
        app.roomInfo.users = data.users
        app.soloInfo.me = data.users.find((item: any) => item.account == app.userInfo.account)
        app.soloInfo.opponent = data.users.find((item: any) => item.account != app.userInfo.account)
        router.push({
            path: "/game",
            query: {
                mode: "quickMatch",
                type: "solo",
            },
        })
    }
}

const buttonHover = () => {
    app.playSound("audio1")
}

const buttonClick = () => {
    app.playSound("audio5")
}

const autoLogin = (key: any) => {
    fetch("autoLogin", { qlKey: key })
        .then((res: any) => {
            if (res.ok) {
                // qlKey有效
                app.isLogin = true
                app.updateUserInfo(res.user)
                // app.showTopMessage('登陆成功', 'success')
                localStorage.setItem("qlKey", res.qlKey) // 更新 qlKey
                loginEnd()
            }
        })
        .catch((err: any) => {
            console.log("err", err)
            app.showMessage(err.msg)
        })
}
// 自动登录
const qlKey = localStorage.getItem("qlKey")
if (qlKey) {
    // 存在qlKey 进行自动登录
    autoLogin(qlKey)
}

// 跳转备案
const toBeiAn = () => {
    // 无反应
    // window.open('https://beian.miit.gov.cn/')
    window.open("https://beian.miit.gov.cn/", "_blank")
}
</script>

<template>
    <div class="pageIndex">
        <div class="bg">
            <div v-if="firstEnter" class="bg3d"></div>
            <!-- v-image-cache需要在初始化后才能调用 -->
            <div v-else class="bg3d" v-image-cache="'bg4'"></div>
        </div>
        <div class="mask"></div>
        <div class="footer" @click="toBeiAn">粤ICP备2025369849号-1</div>
        <vue-particles :class="{ pageIndexParticlesShow: particlesHasInit }" id="pageIndexParticles" :options="Options" @particlesLoaded="particlesLoaded" />
        <login ref="loginEl" @loginEnd="loginEnd" />
        <me ref="meEl" />
        <div ref="listEl" class="list h-full w-full flex flex-col items-end">
            <div @mouseover="buttonHover" class="item" @click="quickMatch(true)" :class="{ hasMatch: hasQuickMatch }">
                <span class="title">{{ $t("index.QUICK_MATCH_title") }}</span>
            </div>
            <div @mouseover="buttonHover" class="item item1" @click="toMulti">
                <span class="title delay1">{{ $t("index.MULTI_title") }}</span>
            </div>
            <div @mouseover="buttonHover" class="item item2" @click="routerPush('/mode', true)">
                <span class="title delay2">{{ $t("index.SINGLE_title") }}</span>
            </div>
            <div @mouseover="buttonHover" class="item item3" @click="routerPush('/tutorial', true)">
                <span class="title delay3">{{ $t("index.Newbie_Tutorial_title") }}</span>
            </div>
            <div @mouseover="buttonHover" class="item item4" @click="routerPush('/build', true)">
                <span class="title delay4">{{ $t("index.FREE_BUILD_title") }}</span>
            </div>
            <div @mouseover="buttonHover" class="item item5" @click="toMe">
                <span class="title delay5">{{ $t("index.ME_title") }}</span>
            </div>
            <div @mouseover="buttonHover" class="item item6" @click="toRank">
                <span class="title delay6">{{ $t("index.RANK_title") }}</span>
            </div>
            <div @mouseover="buttonHover" class="item item7" @click="routerPush('/setting', true)">
                <span class="title delay7">{{ $t("index.SETTING_title") }}</span>
            </div>
        </div>
        <div @click="firstEnterMaskClick" class="firstEnterMask flex items-center justify-center flex-col" :class="{ hide: !firstEnter }">
            <div class="title">Tetris Online</div>
            <div class="tip" v-if="isLoadEnd">click to start</div>
            <div class="tip" v-else>Loading...</div>
            <div class="loading flex items-center" v-if="!isLoadEnd">
                <div class="loadingHypnotic"></div>
                <span v-if="app.audioBase && app.audioBase.loadProgress < 100">{{ app.audioBase.loadProgress }}%</span>
                <span v-else>Loading</span>
            </div>
        </div>
        <!-- 大厅版聊 -->
        <div class="chatBox">
            <div class="chatTitle">Chat</div>
            <div class="chatList" ref="ChatList">
                <div class="chatItem flex items-center" v-for="(i, index) in hallChatList" :key="index">{{ i.user.name }}: {{ i.message }}</div>
            </div>
            <input @keydown.enter="sendMessageHall" type="text" placeholder="message" />
        </div>
    </div>
</template>

<style lang="scss" scoped>
.pageIndex {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    .bg {
        z-index: 0;
        perspective: 10vmin; /* 启用3D空间 */

        .bg3d {
            // background: url("@/assets/bg4.png");
            background-size: cover;
            // background-position: 50% 50%;

            width: 140%;
            height: 120%;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            animation: spaceFloat 50s infinite cubic-bezier(0.4, 0, 0.2, 1);
            transform-style: preserve-3d;

            @keyframes spaceFloat {
                0% {
                    opacity: 1;
                    transform: translate(-50%, -50%) /* 保持居中基准 */ translate3d(0, 0, -1vmin) rotateZ(0.5deg) scale(1);
                }
                25% {
                    opacity: 0.5;
                    transform: translate(-50%, -50%) translate3d(-15%, 10%, 0) rotateZ(-0.8deg) scale(1.05);
                }
                50% {
                    opacity: 1;
                    transform: translate(-50%, -50%) translate3d(10%, -15%, -2vmin) rotateZ(1.2deg) scale(1.1);
                }
                75% {
                    opacity: 0.5;
                    transform: translate(-50%, -50%) translate3d(15%, 10%, -0.5vmin) rotateZ(-1deg) scale(1.07);
                }
                100% {
                    opacity: 1;
                    transform: translate(-50%, -50%) translate3d(0, 0, -1vmin) rotateZ(0.5deg) scale(1);
                }
            }
        }

        img {
            z-index: 1;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }
    .mask {
        z-index: 1;
        backdrop-filter: blur(0.1vmin);
        background: rgba(0, 0, 0, 0.8);
    }
    .bg,
    .mask {
        width: 100%;
        height: 100%;
        position: fixed;
        top: 0;
        left: 0;
    }
    .footer {
        // 备案号
        position: fixed;
        right: 1vmin;
        bottom: 1vmin;
        color: rgb(221, 221, 221, 0.4);
        font-size: 12px;
        z-index: 9999;
        cursor: pointer;
        transition: all 0.2s ease-in-out;
        &:hover {
            color: rgb(221, 221, 221, 0.8);
        }
    }
    #pageIndexParticles {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        pointer-events: none;
        opacity: 0;
    }

    .pageIndexParticlesShow {
        animation: show 1s ease-in-out forwards;
    }
    @keyframes show {
        0% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }
    }

    .firstEnterMask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgb(0, 0, 0, 0.95);
        z-index: 999999;

        &.hide {
            pointer-events: none;
            opacity: 0;
            transition: all 1s ease-in-out;
        }

        .loading {
            font-size: 3vmin;
            position: absolute;
            right: 1vmin;
            bottom: 2vmin;
            color: rgb(221, 221, 221, 0.4);

            .loadingHypnotic {
                width: 4vmin;
                height: 4vmin;
                border: 0.2vmin solid rgb(221, 221, 221, 0.6);
                display: grid;
                animation: hypnotic 3s infinite linear;
                margin-right: 1vmin;

                &::before,
                &::after {
                    content: "";
                    grid-area: 1/1;
                    margin: auto;
                    width: 70.7%;
                    height: 70.7%;
                    border: 0.2vmin solid rgb(221, 221, 221, 0.5);
                    animation: inherit;
                }

                .loadingHypnotic::after {
                    width: 50%;
                    height: 50%;
                    border: 0.2vmin solid rgb(221, 221, 221, 0.4);
                    animation-duration: 2s;
                }
            }

            @keyframes hypnotic {
                100% {
                    transform: rotate(1turn);
                }
            }
        }

        .title {
            font-family: "Floane";
            letter-spacing: 2vmin;
            font-size: 8vmin;
            color: #ddd;
            text-shadow: 0.5vmin 0.5vmin 1vmin rgba(235, 90, 165, 0.8);
            animation: shift 4s ease-in-out infinite alternate;
        }

        .tip {
            font-size: 4vmin;
            margin-top: 20vmin;
            letter-spacing: 0.8vmin;
            color: rgb(221, 221, 221, 0.4);
            animation: firstEnterMaskTip 2s ease-in-out alternate infinite;
        }

        @keyframes firstEnterMaskTip {
            from {
                transform: translateY(0);
                letter-spacing: 0.8vmin;
            }
            to {
                transform: translateY(1vmin);
                letter-spacing: 1vmin;
                opacity: 0.5;
            }
        }
    }

    .list {
        padding: 10vmin 0;
        z-index: 1;
        overflow-x: hidden;
        overflow-y: auto;
        .item {
            width: 100%;
            height: 30%;
            max-height: 150px;
            max-width: 80%;
            display: flex;
            align-items: center;
            padding: 0 10vmin;
            flex-shrink: 0;
            font-size: 6vmin;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s;
            border-radius: 1.5vmin;
            letter-spacing: 1vmin;
            color: hsl(0, 0%, 80%);
            box-shadow: 0px 0px 24px 0px rgba(111, 155, 222, 0.2);
            border: 1px solid rgba(111, 155, 222, 0.3);
            position: relative;
            &:hover {
                transform: scale(1.05) translateY(-3%);
                max-width: 85%;
                background-color: rgba(111, 155, 222, 0.5);
                box-shadow: 0px 0px 24px 0px rgba(111, 155, 222, 0.8);
                letter-spacing: 4vmin;
            }
            &.hasMatch {
                background-image: linear-gradient(310deg, rgb(244, 59, 71, 0.8) 0%, #453a94 100%);
                border: none;
                position: relative;
                z-index: 9;
                &::after {
                    position: absolute;
                    content: "";
                    min-height: 100%;
                    min-width: 100%;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    border-radius: inherit;
                    border: 1px solid rgb(244, 59, 71, 0.5);
                    background: rgb(244, 59, 71, 0.2);
                    opacity: 1;
                    animation: hasMatchOn 0.5s ease-in-out forwards;
                    z-index: 1;
                    pointer-events: none;
                    filter: blur(1px);
                }
                @keyframes hasMatchOn {
                    from {
                        min-height: 100%;
                        min-width: 100%;
                    }
                    to {
                        min-height: 200%;
                        min-width: 200%;
                        opacity: 0;
                    }
                }
            }
            .title {
                animation: shift 4s ease-in-out infinite alternate;
            }
            .delay1 {
                animation-delay: 1s;
            }
            .delay2 {
                animation-delay: 6s;
            }
            .delay3 {
                animation-delay: 4s;
            }
            .delay4 {
                animation-delay: 3s;
            }
            .delay5 {
                animation-delay: 5s;
            }
            .delay6 {
                animation-delay: 2s;
            }
            .delay7 {
                animation-delay: 7s;
            }
        }
        .item1 {
            transform: translateX(5%);
        }
        .item2 {
            transform: translateX(10%);
        }
        .item3 {
            transform: translateX(15%);
        }
        .item4 {
            transform: translateX(20%);
        }
        .item5 {
            transform: translateX(25%);
        }
        .item6 {
            transform: translateX(30%);
        }
        .item7 {
            transform: translateX(35%);
        }
        .item:last-child {
            margin-bottom: 0;
        }
    }

    @keyframes shift {
        0%,
        40%,
        44%,
        58%,
        61%,
        65%,
        69%,
        73%,
        100% {
            transform: skewX(0deg);
        }

        41% {
            transform: skewX(10deg);
        }

        42% {
            transform: skewX(-10deg);
        }

        59% {
            transform: skewX(40deg) skewY(10deg);
        }

        60% {
            transform: skewX(-40deg) skewY(-10deg);
        }

        63% {
            transform: skewX(10deg) skewY(-5deg);
        }

        70% {
            transform: skewX(-50deg) skewY(-20deg);
        }

        71% {
            transform: skewX(10deg) skewY(-10deg);
        }
    }

    .chatBox {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 24vw;
        z-index: 99;
        background: rgba(0, 0, 0, 0.05);
        padding: 2vh 1vw;
        border-radius: 1vmin;
        transition: all 0.5s;
        &:hover {
            box-shadow: 0 0 2px 2px rgba(111, 155, 222, 0.1);
        }
        .chatTitle {
            font-size: 3vmin;
            padding: 2vmin 0;
            color: rgb(221, 221, 221, 0.3);
            letter-spacing: 1vmin;
            text-shadow: 0.5vmin 0.5vmin 1vmin rgba(0, 0, 0.8);
        }
        .chatList {
            max-height: 30vh;
            overflow: auto;
            // 平滑滚动
            scroll-behavior: smooth;
        }
        .chatItem {
            font-size: 2vmin;
            color: rgb(221, 221, 221, 0.5);
            height: 5vmin;
            margin-bottom: 1vh;
        }
        input {
            width: 100%;
            height: 8vmin;
            background: rgba(0, 0, 0, 0.1);
            color: #ddd;
            border-radius: 2vmin;
            transition: all 0.5s;
            font-size: 3vmin;
            padding: 0 1vw;
            &:hover {
                background: rgba(0, 0, 0, 0.3);
            }
        }
    }
}
</style>
